# coding:utf-8
# author:liyao
# 该脚本展示了模拟登录aniu.tv网站的过程

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
import time

class login(object):
    def main (self):
        # 初始化chrome对象，并设置等待时间
        driver = webdriver.Chrome()
        wait = WebDriverWait(driver, 100, ignored_exceptions=None)

        #规避操作，把selenium程序伪装成一个正常的请求，欺骗浏览器。因为selenium在运行的时候会暴露出一些预定义的Javascript变量，例如"navigator.webdriver"，在非selenium环境下其值为undefined，而在selenium环境下，其值为true。
        driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
                Object.defineProperty(navigator, 'webdriver', {
                  get: () => undefined
                })
              """
        })

        driver.maximize_window()
        # 打开网页
        driver.get("https://www.aniu.tv/")
        assert "No results found." not in driver.page_source
        # 点击登录按钮
        wait.until(EC.visibility_of_element_located((By.ID, 'login_href'))).click()
        # 将登录表单切换到账号密码登录选项卡
        wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@class="login_nav"]/a[1]'))).click()
        # 输入用户名和密码
        wait.until(EC.visibility_of_element_located((By.XPATH, '//input[@name="username"]'))).send_keys('13564613025')
        wait.until(EC.visibility_of_element_located((By.XPATH, '//input[@name="password"]'))).send_keys('aniu13564613025')
        # 点击登录按钮
        driver.find_element_by_id('loginBtnByalert').click()

        # 如果出现无感知验证，则模拟通过验证
        # driver.find_element_by_id('loginshowvcode')
        wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@id="SM_BTN_1"]'))).click()

        # 验证是否已登录，查看页面上是否有退出登录按钮
        wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@class="userDataHeader"]/a[@class="userQuitBtn"]')))

        #获取cookies
        cookies = driver.get_cookies()
        print(cookies)

        # 强制等待十秒后关闭浏览器
        time.sleep(10)
        driver.quit()
        print("访问结束")

if __name__ == "__main__":
    aniutv = login()
    aniutv.main()

